/************************************************
 * Copyright (c) 2007 ~ 2009, 
 * All rights reserved.
 * Version   : 1.0
 * Author    : lengsh@alibaba-inc.com 
 * Date      : 2009.1.2
 ************************************************/

#ifndef   __PANDA_MYSQLSTORAGE_H___
#define   __PANDA_MYSQLSTORAGE_H___

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include <mysql.h>
#include <glib.h>
#include <viva.h>
#include "IStorage.h"
#include "Debug.h"

using namespace std;

class MySQLStorage : public  IStorage
{
	public:
                MySQLStorage(){
                        m_pTx = NULL;
#ifdef   _THREAD_SAFE
                        pthread_mutex_init(&_lock, NULL);
                        DEBUG1("pthread_mutex_initi for TXlog");
#endif
                }
                virtual ~MySQLStorage(){
#ifdef  _THREAD_SAFE
                        DEBUG1("pthread_mutex_destroy");
                        pthread_mutex_destroy(&_lock);
#endif
                }
		
		virtual bool Initialize(const char *conf) ;
		virtual int Read(int ihash, GHashTable *kv);
		virtual int Atom(int ihash, const char *key, int &ival, bool bselect);
		virtual int Write(int ihash, GHashTable *kv);
		virtual int Delete(int ihash, GHashTable *kv);
		virtual int SQL(int method, const char *data, unsigned dlen, char **wbuf,unsigned &wsize, unsigned &wbytes);
	protected:
		Viva *m_pTx;
		bool m_bWrite2DB;

		int read_kv_value(MYSQL *conn, int ihash, GHashTable *rkv, GHashTable *kv);
		int write_kv_value(MYSQL *conn, int ihash, const char *key, const char *val, long mt);

		int write_viva(int ihash, const char *key, const char *val, const char *stime, const char *opt = PANDA_CMD_REPLACE) ;
		int write_viva(int ihash, GHashTable *kv, bool iStart, const char *stime, const char *opt = PANDA_CMD_REPLACE);
                int do_MPL(int ihash, const char *data, unsigned dlen, char **wbuf,unsigned &wsize, unsigned &wbytes);
		int do_PQL(int ihash, const char *data, unsigned dlen, char **wbuf,unsigned &wsize, unsigned &wbytes);
		int do_CPL(int ihash, const char *data, unsigned dlen, char **wbuf,unsigned &wsize, unsigned &wbytes);
		int do_SQL(int ihash, const char *data, unsigned dlen, char **wbuf,unsigned &wsize, unsigned &wbytes);

		int fetch_data(MYSQL *conn, const char *sql, unsigned len, char **wbuf, unsigned &wsize, unsigned &wbytes, bool bret);
		int execute_pql(MYSQL *conn, const char *sql, unsigned len);	

#ifdef  _THREAD_SAFE
                pthread_mutex_t _lock;
#endif

};

extern "C" IStorage* create_storage( const char *config);
extern "C" void destroy_storage(MySQLStorage *obj);

#endif  // __PANDA_MYSQLSTORAGE_H___
